import { Button, Table, Modal, message, Form, Input, Space, FormInstance } from 'antd';

import { ColumnsType } from 'antd/lib/table';
import moment from 'moment';
import { checkPermission } from 'permission/Index';
import React from 'react';
import { GetSeatGroupListParams, SeatGroupInfo } from 'admin/schema/SeatGroup';
import { delSeatGroup, getSeatGroupList } from '../../../servers/servers';
import { clearNull, deleteRowChangePageNum, getTableIndex } from '../../../../utils/tools';
import { SeatGroupOperation } from './component/SeatGroupOperation';

interface UserState {
  tableData: SeatGroupInfo[];
  checkDetailVisible: boolean;
  currentRecord: SeatGroupInfo;
  searchForm: any;
  pageInfo: {
    pageNum: number;
    pageSize: number;
    pageTotal: number;
  };
  tableLoading: boolean;
}

export default class SeatGroup extends React.Component<{}, UserState> {
  // table 列
  columns: ColumnsType<SeatGroupInfo>;
  formRef = React.createRef<FormInstance>();
  // 坐席组操作控件引用
  SeatGroupOperationRef: React.RefObject<SeatGroupOperation>;

  constructor(props: {}) {
    super(props);
    this.SeatGroupOperationRef = React.createRef();
    this.state = {
      tableData: [],
      checkDetailVisible: false,
      searchForm: {},
      currentRecord: {} as SeatGroupInfo,
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: false,
    };
    this.columns = [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        key: 'index',
        render: (text, record, index) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      },
      {
        title: '组名',
        dataIndex: 'seatGroupName',
        key: 'seatGroupName',
      },

      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        render: (text, record, index) => {
          return moment(Number(text)).format('YYYY-MM-DD HH:mm');
        },
      },
      {
        title: '坐席数',
        dataIndex: 'seatNumber',
        key: 'seatNumber',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        width: 240,
        render: (text, record, index) => {
          return (
            <>
              {checkPermission('/account/seatGroup/modify') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.modify(record);
                  }}
                >
                  编辑
                </Button>
              )}
              {checkPermission('/account/seatGroup/adjust') && (
                <Button
                  type="link"
                  onClick={() => {
                    const id = record.seatGroupId;
                    console.log('调整坐席', id);
                    const route = (this.props as any).history;
                    route.push(`/webapp/account/seatGroup/adjust?seatGroupId=${id}`);
                  }}
                >
                  调整坐席
                </Button>
              )}
              {checkPermission('/account/seatGroup/delete') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.deleteRecord(record);
                  }}
                >
                  删除
                </Button>
              )}
            </>
          );
        },
      },
    ];
  }

  componentDidMount() {
    this.fetchList();
  }

  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  };

  /**
   * 编辑坐席组
   */
  private modify(record: SeatGroupInfo): void {
    this.SeatGroupOperationRef.current?.open('modify', record);
  }
  /**
   * 删除数据后更新
   */
  private deleteFresh(size: number) {
    const { pageTotal, pageNum, pageSize } = this.state.pageInfo;
    const newPageNum = deleteRowChangePageNum(size, pageTotal, pageNum, pageSize);
    this.setState(
      {
        pageInfo: {
          pageTotal,
          pageSize,
          pageNum: newPageNum,
        },
      },
      () => {
        this.fetchList();
      }
    );
  }
  /**
   * 删除坐席组
   */
  private deleteRecord(record: SeatGroupInfo): void {
    Modal.confirm({
      content: '删除后无法恢复，确认删除吗',
      onOk: () => {
        delSeatGroup(record.seatGroupId as number)
          .then(res => {
            message.success('删除成功');
            this.deleteFresh(1);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }

  /**
   * 查询当前列表
   */
  private async fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { pageInfo, searchForm } = this.state;
    const params: GetSeatGroupListParams = {
      ...searchForm,
      pageNo: pageInfo.pageNum,
      pageSize: pageInfo.pageSize,
    };
    try {
      const { count = 0, data = [] } = await getSeatGroupList(clearNull(params));
      pageInfo.pageTotal = count;
      this.setState({
        tableData: data,
        pageInfo,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      tableLoading: false,
    });
  }

  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }

  /**
   * 查询操作，提交查询条件
   */
  handleSearch = (values: any) => {
    this.setState(
      {
        searchForm: { ...values },
      },
      () => {
        this.jumpPage(1);
      }
    );
  };

  /**
   * 重置查询操作
   */
  handleReset = () => {
    this.formRef.current?.resetFields();
    this.setState(
      {
        searchForm: {},
      },
      () => {
        this.jumpPage(1);
      }
    );
  };

  render() {
    const {
      tableData,
      tableLoading,
      pageInfo: { pageNum, pageSize, pageTotal },
    } = this.state;
    const { columns, SeatGroupOperationRef } = this;

    return (
      <div className="user-mgr">
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Form layout="inline" ref={this.formRef} onFinish={this.handleSearch}>
              <Form.Item
                label=""
                name="condition"
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input allowClear placeholder="请输入组名/坐席工号" />
              </Form.Item>
              <Form.Item
                label="坐席姓名"
                name="nickName"
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input allowClear placeholder="请输入" style={{ width: 200 }} />
              </Form.Item>
              <Space size="middle">
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button type="primary" ghost onClick={this.handleReset}>
                  重置
                </Button>
              </Space>
            </Form>
          </div>
          <div className="mgr-header-right">
            {checkPermission('/account/seatGroup/add') && (
              <Button
                type="primary"
                onClick={() => {
                  this.SeatGroupOperationRef.current?.open('create');
                }}
              >
                新建坐席组
              </Button>
            )}
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            scroll={{ x: 'max-content' }}
            columns={columns}
            dataSource={tableData}
            rowKey="seatGroupId"
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <SeatGroupOperation
          ref={SeatGroupOperationRef}
          callback={id => {
            id ? this.fetchList() : this.jumpPage(1);
          }}
        />
      </div>
    );
  }
}
